<template>
  <div class="todaySubscribeList">
    <x-header class="header" :left-options="{showBack: showHeaderBack,preventGoBack:true}" @on-click-back="goToPage" ref="header">今日预订列表</x-header>
    <div class="topHolder"></div>
    <box gap="1rem 0.8rem 0.8rem">
      <div class="topBtn" ref="topBtn">
        <checker v-if="loadingStatus" v-model="selfHelpCustomer" default-item-class="checker" selected-item-class="checker-selected" disabled-item-class="checker-disabled">
          <checker-item value="-1" :disabled="loadingStatus">自来客</checker-item>
        </checker>
        <checker v-else v-model="selfHelpCustomer" @on-change="refreshList()" default-item-class="checker" selected-item-class="checker-selected" disabled-item-class="checker-disabled">
          <checker-item value="true">自来客</checker-item>
        </checker>
      </div>
      <div class="filterArea" ref="filterArea">
        <div class="filterItem"><x-button @click.native="showUsersByDepart = true" type="default" v-html="usersByDepartText" :show-loading="loadingStatus" :disabled="loadingStatus" class="inlineBtn popPickerBtn"></x-button></div>
      </div>
      <popup-picker @on-change="changeUsersByDepartText();refreshList()" :show.sync="showUsersByDepart" :show-cell="false" :data="usersByDepart" :columns="2" v-model="choosenDepartAndUser" ref="usersByDepart" class="btn_popup-picker"></popup-picker>
      <group-title ref="subscribeTotals" class="subscribeTotals">
        今天预订数量：
        <span v-for="(item,index) in subscribeTotals" :key="index">
          <span v-text="item.name"></span>（<span v-text="item.total"></span>）
        </span>
      </group-title>
    </box>
    <scroller :height="scrollerHeight" lock-x use-pulldown use-pullup :pulldown-config="pulldownDefaultConfig" @on-pulldown-loading="refreshList()" :pullup-config="pullupDefaultConfig" @on-pullup-loading="loadMoreList" ref="loadMoreScroller" >
      <div class="subscribeList">
        <a v-for="(item,index) in subscribeList" :key="index" @click="toDetail(item.SUBSCRIBE_ID)">
          <form-preview class="formPreviewList label" :class="[getStateClass(item.SUBSCRIBE_MODE)]" :header-label="'预订房台类型：' + (item.SUBSCRIBE_ROOM_PLATFORM_TYPE?item.SUBSCRIBE_ROOM_PLATFORM_TYPE:'无法显示类型')" :header-value="getState(item.SUBSCRIBE_MODE)" :body-items="getBody(item)"></form-preview>
        </a>
        <div class="listNoItem" v-if="subscribeList.length <= 0">暂无预订</div>
      </div>
    </scroller>
  </div>
</template>

<script>
  import {XButton, Checker, CheckerItem, Box, PopupPicker, GroupTitle, FormPreview, Scroller } from 'vux'
  import {getUsersByDepart,getTodaySubscribeIdList,getSubscribeByIds,getSubscribeTotals} from "../../api";
  import {message} from "../../common/util";

  export default {
    name:'todaySubscribeList',
    data(){
      return{
        showHeaderBack:this.GLOBAL.showHeaderBack,
        loadingStatus:false,
        selfHelpCustomer:[],
        usersByDepartText:'',
        showUsersByDepart: false,
        choosenDepartAndUser:['allDepart','allPerson'],
        subscribeTotals:[],
        subscribeList:[],
        idArrayList:[],
        scrollerHeight:'',
        pulldownDefaultConfig:{
          content: '下拉刷新',
          height: 40,
          autoRefresh: false,
          downContent: '下拉刷新',
          upContent: '释放后刷新',
          loadingContent: '正在刷新...',
          clsPrefix: 'xs-plugin-pulldown-'
        },
        pullupDefaultConfig:{
          content: '上拉加载更多',
          pullUpHeight: 60,
          height: 40,
          autoRefresh: false,
          downContent: '释放后加载',
          upContent: '上拉加载更多',
          loadingContent: '加载中...',
          clsPrefix: 'xs-plugin-pullup-'
        },
        currentPage: 0,
        totalItems:0,
        pageSize:8,
        onFetching:true
      }
    },
    components:{
      XButton,
      Checker,
      CheckerItem,
      Box,
      PopupPicker,
      GroupTitle,
      FormPreview,
      Scroller
    },
    computed:{
      authority(){
        return this.$store.getters.getAuthority
      },
      usersByDepart:{
        get(){
          return this.$store.getters.getUsersByDepart_all
        },
        set(value){
          this.$store.commit('updateUsersByDepart_all', value)
        }
      }
    },
    methods:{
      goToPage(){
        this.$router.push({path:'/'})
      },
      getState(type){
        switch (type) {
          case 1:return '微信自助预订';break
          case 2:return '销售预订';break
          case 3:return '老板预订';break
          case 4:return '股东预订';break
          default:return '无预订类型';break
        }
      },
      getStateClass(state){
        switch (state) {
          case 1:return 'orange';break
          case 2:return 'green';break
          case 3:return 'red';break
          case 4:return 'blue';break
          default:return 'gray';break
        }
      },
      getBody(item){
        let list = [],name = item.CUSTOMER_NAME?item.CUSTOMER_NAME:'未填写姓名'
        list.push({label:'预订时间',value:item.SUBSCRIBE_DATETIME})
        list.push({label:'预订客户',value:name + '-' + item.PHONE})
        list.push({label:'点击查看详情>>',value:''})
        return list
      },
      toDetail(id){
        //this.$router.push({name:'分配预订详情',params:{subscribeId:id}})
        this.$router.push({name:'预订详情',params:{subscribeId:id,type:'view'}})
      },
      refreshList(params){
        this.loadingStatus = true
        this.subscribeList = []
        this.currentPage = 0
        let reqParams = {
          choosenDepartAndUser:this.choosenDepartAndUser,
          selfHelpCustomer:this.selfHelpCustomer.length > 0?true:false
        }
        getTodaySubscribeIdList(reqParams).then((res)=>{
          if(res.status == 'success'){
            this.$nextTick(() => {
              if(this.$refs.loadMoreScroller) {
                this.$refs.loadMoreScroller.reset({top: 0})
                this.$refs.loadMoreScroller.donePulldown()
              }
              this.idArrayList = res.data
              this.totalItems = res.data.length
              this.loadMoreList({callback:(params && params.callback)?params.callback:null})
            })
          }else if(res.status == 'error') {
            message({message:res.msg,type:'error'})
            console.log('getSubscribeIdList error info:', res.msg)
          }
        }).catch((err)=>{console.log('getSubscribeIdList catch info:',err)})
      },
      loadMoreList(params){
        if (this.onFetching) {
          this.onFetching = false
          setTimeout(() => {
            let reqParams = [],start = this.currentPage*this.pageSize,end = start + this.pageSize - 1
            for(var i = start; i <= end; i++){
              if(this.idArrayList[i] != undefined)reqParams.push(this.idArrayList[i])
            }
            getSubscribeByIds(reqParams).then((res)=>{
              if(res.status == 'success'){
                if(res.data.length > 0){//后端实际用这个
                  //if (this.subscribeList.length < this.totalItems) {//前端测试用这个
                  for(var i = 0; i < res.data.length; i++){
                    this.subscribeList.push(res.data[i])
                  }
                  this.currentPage++
                }else{
                  message({message:'已经加载到底了！',type:'info'})
                }
                this.onFetching = true
                this.$nextTick(() => {
                  if(this.$refs.loadMoreScroller != undefined){
                    this.$refs.loadMoreScroller.donePullup()
                    this.$refs.loadMoreScroller.reset()
                  }
                })
              }else if(res.status == 'error') {
                message({message:res.msg,type:'error'})
                console.log('getSubscribeByIds error info:', res.msg)
              }
              this.setSize()
              this.loadingStatus = false
              if(params && params.callback && typeof params.callback == 'function')params.callback()
            }).catch((err)=>{console.log('getSubscribeByIds catch info:',err)})
          }, 1)
        }
      },
      setSize(){
        let outHeight = 0
        if(this.$refs.header)
          outHeight = this.$refs.header.$el.offsetHeight + this.$refs.filterArea.offsetHeight + this.$refs.subscribeTotals.$el.offsetHeight
        let contentHeight = window.screen.height - outHeight - 150
        this.scrollerHeight = contentHeight + 'px'
      },
      changeUsersByDepartText(text){
        this.usersByDepartText = text?(text+'<i class=\'iconfont icon-xiangxia2\'></i>'):(this.$refs.usersByDepart&&this.$refs.usersByDepart.getNameValues().replace(/ /g,' / ')+'<i class=\'iconfont icon-xiangxia2\'></i>')
      }
    },
    mounted(){
      let funcArray = [getSubscribeTotals('manager')]
      if(this.usersByDepart.length <= 0) funcArray.push(getUsersByDepart('manager'))
      Promise.all(funcArray).then((res)=> {
        for(let dataObj of res){
          if(dataObj.status == 'success'){
            if(dataObj.data.length > 0 && dataObj.data[0].value) this.usersByDepart = dataObj.data
            else if(dataObj.data.length > 0 && dataObj.data[0].total >= 0) this.subscribeTotals = dataObj.data
          }else if(dataObj.status == 'error') {
            message({message:dataObj.msg,type:'error'})
            console.log('getUsersByDepart & getSubscribeTotals error info:', dataObj.msg)
          }
        }
      }).then(()=>{
        this.choosenDepartAndUser = ['allDepart','allPerson']
        setTimeout(()=>{this.changeUsersByDepartText(this.usersByDepart[0].name + ' / ' + this.usersByDepart[1].name)},200)
        this.refreshList({callback: ()=>{
            window.onresize = ()=>{
              this.setSize()
            }
          }})
        this.$store.commit('updateLoadingStatus',{isLoading:false})
      })
    },
    beforeDestroy(){
      window.onresize = ()=>{}
    }
  }
</script>

<style lang="scss" scoped>
  .todaySubscribeList{
    .topBtn{
      text-align: right;
      .checker{background-color: #ddd;color: #222;font-size: 1rem;padding: 0.2rem 1rem;line-height: 1.5rem;border-radius: 0.3rem;}
      .checker-selected{background-color: #FF3B3B;color: #fff;}
      .checker-disabled{background-color: #6d6d6d;}
    }
    .filterArea{
      .filterItem{margin-top: 0.5rem;}
    }
    .subscribeTotals{margin: 0.5rem 0;}
  }
</style>
